package com.example.autopia.view.Activities

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.autopia.R
import com.example.autopia.R.*
import com.example.autopia.databinding.ActivityMyCarsBinding
import com.example.autopia.model.Item.Car
import com.example.autopia.model.Item.News
import com.example.autopia.model.Item.Parking
import com.example.autopia.model.Repositories.TestRepository
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.view.Adapters.ColorItemAdapter
import com.example.autopia.view.Adapters.MyCarAdapter
import com.example.autopia.view.Listeners.ColorItemListener
import com.example.autopia.view.Listeners.MyCarsListener
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase

class MyCarsActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMyCarsBinding
    private lateinit var tvColor: TextView

    val carAdapter = MyCarAdapter()
    private val userRepository = UsersRepository()
    private val firebaseAuth = Firebase.auth
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMyCarsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.recyclerView.adapter = carAdapter
        binding.btBack.setOnClickListener {
            onBackPressed()
        }
        val list = ArrayList<Car>()
        list.add(TestRepository.getCar())
        list.add(list.size, Car("1", "1", "1", 1))
        carAdapter.setData(list)

        setUserData()

        carAdapter.attachListener(object : MyCarsListener {
            override fun onEditClicked(car: Car, isAdd: Boolean) {
                showDialog(car, isAdd)
            }
        })
    }

    private fun setUserData () {
        val user = userRepository.getUserById(firebaseAuth.currentUser?.uid ?: "")
        user.observe(this) { curUser ->
            val cars = ArrayList<Car>()
            if (curUser.carsList.isNullOrEmpty()) {
                cars.add(cars.size, Car("1", "1", "1", 1))
                carAdapter.setData(cars)
                binding.recyclerView.visibility = View.VISIBLE
                binding.loading.visibility = View.GONE
            } else {
                cars.addAll(curUser.carsList)
                cars.add(cars.size, Car("1", "1", "1", 1))
                carAdapter.setData(cars)
                binding.recyclerView.visibility = View.VISIBLE
                binding.loading.visibility = View.GONE
            }
        }
    }

    private fun showDialog(car: Car, isAdd: Boolean) {
        val dialog = Dialog(this@MyCarsActivity)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(layout.dialog_car_edit_add)

        val etModel = dialog.findViewById<EditText>(id.etModel)
        tvColor = dialog.findViewById<TextView>(id.tvColor)
        val etNumber = dialog.findViewById<EditText>(id.etNumber)
        val btSave = dialog.findViewById<ImageButton>(id.btToSave)
        val tvDialogTitle = dialog.findViewById<TextView>(id.tvDialogTitle)
        val btClose = dialog.findViewById<ImageButton>(id.btClose)
        val llDelete = dialog.findViewById<LinearLayout>(id.llDeleteAuto)

        tvColor.setOnClickListener {
            showDialogChoiceColor()
        }

        if (isAdd) {
            tvDialogTitle.text = "Добавление"
        } else {
            tvDialogTitle.text = "Редактирование"
            llDelete.visibility = View.VISIBLE
            etModel.setText(car.model)
            etModel.isEnabled = false
            tvColor.text = getColor(car.color)
            etNumber.setText(car.number)
            etNumber.isEnabled = false
        }
        btSave.setOnClickListener {
            if (isAdd) {
                val userCar = Car(
                    etModel.text.toString(),
                    etNumber.text.toString(),
                    getCodeColor(tvColor.text.toString())
                )
                userRepository.addCar(Firebase.auth.currentUser!!.uid, userCar)
            } else {
                userRepository.changeCarColor(
                    Firebase.auth.currentUser!!.uid,
                    car.number,
                    getCodeColor(tvColor.text.toString())
                )
            }
            setUserData()
            dialog.dismiss()
        }
        btClose.setOnClickListener {
            dialog.dismiss()
        }

        llDelete.setOnClickListener {
            userRepository.deleteCar(Firebase.auth.currentUser!!.uid, car.number)
            setUserData()
            dialog.dismiss()
            Toast.makeText(dialog.context, "Автомобиль удален", Toast.LENGTH_SHORT).show()
        }

        dialog.show()
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.window?.attributes!!.windowAnimations = style.DialogAnimation
        dialog.window?.setGravity(Gravity.BOTTOM)
    }

    private fun getColor(color: String): String {
        return when (color) {
            "black" -> "Чёрный"
            "red" -> "Красный"
            "orange" -> "Оранжевый"
            "yellow" -> "Жёлтый"
            "green" -> "Зелёный"
            "blue_light" -> "Голубой"
            "blue" -> "Синий"
            "purple" -> "Фиолетовый"
            "pink" -> "Розовый"
            "brown" -> "Коричневый"
            "grey" -> "Серый"
            "white" -> "Белый"
            else -> "Чёрный"
        }
    }

    private fun getCodeColor(color: String): String {
        return when (color) {
            "Чёрный" -> "black"
            "Красный" -> "red"
            "Оранжевый" -> "orange"
            "Жёлтый" -> "yellow"
            "Зелёный" -> "green"
            "Голубой" -> "blue_light"
            "Синий" -> "blue"
            "Фиолетовый" -> "purple"
            "Розовый" -> "pink"
            "Коричневый" -> "brown"
            "Серый" -> "grey"
            "Белый" -> "white"
            else -> "black"
        }
    }

    private fun showDialogChoiceColor() {
        val dialog = Dialog(this@MyCarsActivity)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(layout.dialog_choise_color)

        val rec = dialog.findViewById<RecyclerView>(id.ColorList)
        val btClose = dialog.findViewById<ImageButton>(id.btClose)

        val list = ArrayList<String>()
        list.add("Чёрный")
        list.add("Красный")
        list.add("Оранжевый")
        list.add("Жёлтый")
        list.add("Зелёный")
        list.add("Голубой")
        list.add("Синий")
        list.add("Фиолетовый")
        list.add("Коричневый")
        list.add("Серый")
        list.add("Белый")
        list.add("Розовый")
        val adapter = ColorItemAdapter()
        rec.adapter = adapter
        adapter.setData(list)

        adapter.attachListener(object : ColorItemListener {
            override fun onColorItemClicked(color: String) {
                dialog.dismiss()
                tvColor.text = color
            }
        })

        btClose.setOnClickListener {
            dialog.dismiss()
        }
        dialog.show()
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.window?.attributes!!.windowAnimations = style.DialogAnimation
        dialog.window?.setGravity(Gravity.BOTTOM)
    }
}